package cool.doudou.doudada.cipher.algorithm.util;

import cool.doudou.doudada.cipher.algorithm.enums.Algorithm;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 消息认证码
 *
 * @author jiangcs
 * @since 2022/08/24
 */
public class HmacUtil {
    /**
     * MD5
     *
     * @param encryptKey 加密Key
     * @param plaintext  明文
     * @return 加密字符串
     */
    public static String md5(String encryptKey, String plaintext) {
        try {
            SecretKey secretKey = new SecretKeySpec(encryptKey.getBytes(StandardCharsets.UTF_8), Algorithm.HmacMD5.code());
            Mac mac = Mac.getInstance(Algorithm.HmacMD5.code());
            mac.init(secretKey);

            byte[] rawHmac = mac.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(rawHmac);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * SHA1
     *
     * @param encryptKey 加密Key
     * @param plaintext  明文
     * @return 加密字符串
     */
    public static String sha1(String encryptKey, String plaintext) {
        try {
            SecretKey secretKey = new SecretKeySpec(encryptKey.getBytes(StandardCharsets.UTF_8), Algorithm.HmacSHA1.code());
            Mac mac = Mac.getInstance(Algorithm.HmacSHA1.code());
            mac.init(secretKey);

            byte[] rawHmac = mac.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(rawHmac);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * SHA256
     *
     * @param encryptKey 加密Key
     * @param plaintext  明文
     * @return 加密字符串
     */
    public static String sha256(String encryptKey, String plaintext) {
        try {
            SecretKey secretKey = new SecretKeySpec(encryptKey.getBytes(StandardCharsets.UTF_8), Algorithm.HmacSHA256.code());
            Mac mac = Mac.getInstance(Algorithm.HmacSHA256.code());
            mac.init(secretKey);

            byte[] rawHmac = mac.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(rawHmac);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
